package com.ts.api.http.org.base;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.reflection.ClassConvertUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.ts.api.http.org.base.entity.apply.BaseOrgApplyQingYu;
import com.ts.api.http.org.base.entity.apply.BaseOrgApplyQingYuData;
import com.ts.api.http.org.base.entity.dataexchange.BaseOrgDataExchangeQingYu;
import com.ts.api.http.org.utils.ApiQingYuUtils;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.org.handler.ApiOrgPhoneMd5ConvertHandler;
import com.ts.api.module.api.convert.org.model.RespOrgPhoneMd5Apply;
import com.ts.api.module.api.convert.org.model.RespOrgPhoneMd5DataExchange;

import java.util.List;
import java.util.Map;

/**
 *  庆鱼
 */
public class ApiOrgPhoneMd5QingYu implements ApiOrgPhoneMd5ConvertHandler {

    private final String accessKey;
    private final String publicKey;
    private final String t7;

    public ApiOrgPhoneMd5QingYu(String accessKey, String publicKey, String t7) {
        this.accessKey = accessKey;
        this.publicKey = publicKey;
        this.t7 = t7;
    }

    @Override
    public String dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) {
        BaseOrgDataExchangeQingYu dataExchangeHX = new BaseOrgDataExchangeQingYu();
        dataExchangeHX.setAccessKey(accessKey);
        dataExchangeHX.setRequestId(apiDataExchangeParameter.getReqId());
        Map<String, Object> dataMap = MapUtils.newHashMap(map -> map.put("phone", apiDataExchangeParameter.getPhoneMd5()));
        dataExchangeHX.setData(CollUtils.newArrayList(list -> list.add(dataMap)));

        String sendJson = JsonUtils.toJson(dataExchangeHX);
        return sendJson;
    }

    /**
     *  通用判断成功方法
     *
     *  @param respJson
     *  @return
     */
    public boolean hasSuc(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return false;
        }
        boolean code = Eq.object(jsonObject.getInteger("code"), 200);
        Boolean success = jsonObject.getBoolean("success");
        return code && success;
    }

    @Override
    public RespOrgPhoneMd5DataExchange respDataExchange(String respJson) {
        boolean b = hasSuc(respJson);
        if (!b) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }
        JSONObject jsonObject = JsonUtils.get(respJson);
        JSONArray data = jsonObject.getJSONArray("data");
        if (data == null) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }

        //  空数据才成功
        int size = data.size();
        if (!(size == 0)) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }
        return RespOrgPhoneMd5DataExchange.ofSuc();
    }

    @Override
    public String apply(ApiApplyParameter apiApplyParameter) {
        BaseOrgApplyQingYu apply = new BaseOrgApplyQingYu();
        apply.setAccessKey(accessKey);
        apply.setRequestId(apiApplyParameter.getReqId());

        List<BaseOrgApplyQingYuData> list = CollUtils.newArrayList(newList -> {
            BaseOrgApplyQingYuData applyData = new BaseOrgApplyQingYuData();
            applyData.setT1(apiApplyParameter.getPhone());
            applyData.setT2(apiApplyParameter.getUserName());

            //  客户类型
            String career = apiApplyParameter.getCareer();
            if (ValidParam.isEmpty(career)) {
                //  无数据为个人用户
                applyData.setT3("1");
            } else {
                String choose = ChooseEq.create()
                    //  如果是企业就为企业用户
                    .when(career, "3", "2")
                    //  个人用户
                .end("1");
                applyData.setT3(choose);
            }

            //  贷款额度
            if (ValidParam.isNotEmpty(apiApplyParameter.getLoanAmount())) {
                String money = ChooseEq.create()
                    .when(apiApplyParameter.getLoanAmount(), "1", "30000")
                    .when(apiApplyParameter.getLoanAmount(), "2", "50000")
                    .when(apiApplyParameter.getLoanAmount(), "3", "100000")
                    .when(apiApplyParameter.getLoanAmount(), "4", "200000")
                .end();
                applyData.setT4(money);
            }

            //  标识
            applyData.setT7(t7);

            String areaCode = apiApplyParameter.getAreaCode();
            //  省编码
            applyData.setT8(areaCode.substring(0, 2) + "0000");
            //  市编码
            applyData.setT9(areaCode);
            //  拓展信息
            applyData.setT10(getT10Text(apiApplyParameter));
            //  加密数据
            ApiQingYuUtils.encryptData(applyData, publicKey);

            newList.add(applyData);
        });
        apply.setData(list);

        String sendJson = JsonUtils.toJson(apply);
        return sendJson;
    }

    @Override
    public RespOrgPhoneMd5Apply respApply(String respJson) {
        boolean b = hasSuc(respJson);
        if (b) {
            //  判断是否有手机号重复字眼
            JSONObject json = JsonUtils.get(respJson);
            String data = json.getString("data");
            if (ValidParam.isEmpty(data)) {
                return RespOrgPhoneMd5Apply.ofFail();
            }
            if (data.contains("重复")) {
                return RespOrgPhoneMd5Apply.ofFail();
            }
        }
        if (!b) {
            return RespOrgPhoneMd5Apply.ofFail();
        }
        return RespOrgPhoneMd5Apply.ofSuc();
    }

    public static String getT10Text(ApiApplyParameter apiApplyParameter) {
        StringBuilder stringBuilder = new StringBuilder();

        //  年龄
        if (ValidParam.isNotEmpty(apiApplyParameter.getAge())) {
            Integer age = ChooseEq.create()
                    .when(apiApplyParameter.getAge(), "1", 18)
                    .when(apiApplyParameter.getAge(), "2", 25)
                    .when(apiApplyParameter.getAge(), "3", 57)
                    .end(ClassConvertUtils.toInt(apiApplyParameter.getAge()));
            stringBuilder.append("年龄：").append(age).append(";").append("\n");
        }

        //  性别
        if (ValidParam.isNotEmpty(apiApplyParameter.getSex())) {
            String sex = ChooseEq.create()
                    .when(apiApplyParameter.getSex(), "0", "男")
                    .when(apiApplyParameter.getSex(), "1", "女")
                    .end("");
            stringBuilder.append("性别：").append(sex).append(";").append("\n");
        }

        //  信用记录-逾期记录
        if (ValidParam.isNotEmpty(apiApplyParameter.getOverdue())) {
            String text = ChooseEq.create()
                    .when(apiApplyParameter.getOverdue(), "1", "无逾期")
                    .when(apiApplyParameter.getOverdue(), "2", "有逾期")
                    .when(apiApplyParameter.getOverdue(), "3", "一年以内无逾期")
                    .end();
            stringBuilder.append("信用记录：").append(text).append(";").append("\n");
        }

        //  芝麻分
        if (ValidParam.isNotEmpty(apiApplyParameter.getSesameCredit())) {
            String text = ChooseEq.create()
                    .when(apiApplyParameter.getSesameCredit(), "1", "600分以下")
                    .when(apiApplyParameter.getSesameCredit(), "2", "600~649分")
                    .when(apiApplyParameter.getSesameCredit(), "3", "650~699分")
                    .when(apiApplyParameter.getSesameCredit(), "4", "700分以上")
                    .end();
            stringBuilder.append("芝麻分：").append(text).append(";").append("\n");
        }

        //  职业
        if (ValidParam.isNotEmpty(apiApplyParameter.getCareer())) {
            String text = ChooseEq.create()
                    .when(apiApplyParameter.getCareer(), "1", "上班族")
                    .when(apiApplyParameter.getCareer(), "2", "自由职业")
                    .when(apiApplyParameter.getCareer(), "3", "企业主（有营业执照）")
                    .when(apiApplyParameter.getCareer(), "4", "公务员或事业单位")
                    .end();
            stringBuilder.append("职业：").append(text).append(";").append("\n");
        }

        //  学历
        if (ValidParam.isNotEmpty(apiApplyParameter.getEducationAttainment())) {
            String text = ChooseEq.create()
                    .when(apiApplyParameter.getEducationAttainment(), "1", "初中及以下")
                    .when(apiApplyParameter.getEducationAttainment(), "2", "中专")
                    .when(apiApplyParameter.getEducationAttainment(), "3", "高中")
                    .when(apiApplyParameter.getEducationAttainment(), "4", "大专")
                    .when(apiApplyParameter.getEducationAttainment(), "5", "本科")
                    .when(apiApplyParameter.getEducationAttainment(), "6", "研究生及以上")
                    .end();
            stringBuilder.append("学历：").append(text).append(";").append("\n");
        }

        //  收入形式
        if (ValidParam.isNotEmpty(apiApplyParameter.getSalaryPayMethod())) {
            String text = ChooseEq.create()
                    .when(apiApplyParameter.getSalaryPayMethod(), "1", "银行代发打卡")
                    .when(apiApplyParameter.getSalaryPayMethod(), "2", "现金收入")
                    .when(apiApplyParameter.getSalaryPayMethod(), "3", "个人转账")
                    .end();
            stringBuilder.append("收入形式：").append(text).append(";").append("\n");
        }

        //  客户类型
        String career = apiApplyParameter.getCareer();
        if (ValidParam.isEmpty(career)) {
            //  无数据为个人用户
            stringBuilder.append("客户类型：").append("个人").append(";").append("\n");
        } else {
            String text = ChooseEq.create()
                    //  如果是企业就为企业用户
                    .when(career, "3", "企业")
                    //  个人用户
                    .end("个人");
            stringBuilder.append("客户类型：").append(text).append(";").append("\n");
        }

        //  房产情况
        if (ValidParam.isNotEmpty(apiApplyParameter.getRealEstateInfo())) {
            String text = ChooseEq.create()
                    .when(apiApplyParameter.getRealEstateInfo(), "1", "无")
                    .end("有");
            stringBuilder.append("房产情况：").append(text).append(";").append("\n");
        }

        //  车产
        if (ValidParam.isNotEmpty(apiApplyParameter.getCarInfo())) {
            String text = ChooseEq.create()
                    .when(apiApplyParameter.getCarInfo(), "1", "无")
                    .end("有");
            stringBuilder.append("车辆情况：").append(text).append(";").append("\n");
        }

        //  保单
        if (ValidParam.isNotEmpty(apiApplyParameter.getInsurancePolicy())) {
            String text = ChooseEq.create()
                    .when(apiApplyParameter.getInsurancePolicy(), "1", "无")
                    .end("有");
            stringBuilder.append("保单：").append(text).append(";").append("\n");
        }

        //  社保
        if (ValidParam.isNotEmpty(apiApplyParameter.getSocialSecurity())) {
            String text = ChooseEq.create()
                    .when(apiApplyParameter.getSocialSecurity(), "1", "无")
                    .end("有");
            stringBuilder.append("社保：").append(text).append(";").append("\n");
        }

        //  公积金
        if (ValidParam.isNotEmpty(apiApplyParameter.getProvidentFund())) {
            String text = ChooseEq.create()
                    .when(apiApplyParameter.getProvidentFund(), "1", "无")
                    .end("有");
            stringBuilder.append("公积金：").append(text).append(";").append("\n");
        }

        //  银行代发
        if (ValidParam.isNotEmpty(apiApplyParameter.getSalaryPayMethod())) {
            String text = ChooseEq.create()
                    .when(apiApplyParameter.getSalaryPayMethod(), "1", "是")
                    .end("否");
            stringBuilder.append("银行代发：").append(text).append(";").append("\n");
        }
        return stringBuilder.toString();
    }
}
